package com.demo.juc.futuretask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName CompletableFutureTaskMulti
 * @Author bsy
 * @Description 功能 --》性能 ： CompletableFuture + Lamada表达式
 *
 * 对比前后用时
 *
 * @Date 2022/9/27 22:50
 * @Version 1.0
 */
public class CompletableFutureTaskMulti {

    public static void main(String[] args) {

        List<NumCounter> list = new ArrayList<>();
        NumCounter c1 = new NumCounter("刘备");
        NumCounter c2 = new NumCounter("关羽");
        NumCounter c3 = new NumCounter("张飞");
        list.add(c1);
        list.add(c2);
        list.add(c3);


        long startTime1 = System.currentTimeMillis();
        // 一般常规执行
        list.stream().forEach(c-> System.out.println(String.format("%s 报数：%s",c.getName(),c.getNum())));

        //使用parallelStream ForkJion
        //list.parallelStream().forEach(c-> System.out.println(String.format("%s 报数：%s",c.getName(),c.getNum())));

        long endTime1 = System.currentTimeMillis();
        System.out.println("一般执行总用时；" + (endTime1 - startTime1) + "ms");

        System.out.println("=============对比上下==============");

        long startTime2 = System.currentTimeMillis();
        list.stream()
                .map(c-> CompletableFuture.supplyAsync(()->{return String.format("%s 报数：%s",c.getName(),c.getNum());}))
                .collect(Collectors.toList())
                .stream()
                .map(c->c.join())
                .forEach(System.out::println);

        long endTime2 = System.currentTimeMillis();
        System.out.println("异步并行，执行总用时；" + (endTime2 - startTime2) + "ms");
    }


    static class NumCounter {
        private String name;

        public NumCounter(String name) {
            this.name = name;
        }

        public String getNum() {
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            return String.valueOf(ThreadLocalRandom.current().nextInt());
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
